import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../../core/models/leaderboard_comment_entity.dart';
import '../../../core/di/service_locator.dart';

/// 弹幕评论组件
/// 实现类似弹幕的滚动评论效果
class DanmakuCommentWidget extends StatefulWidget {
  final double height;
  final int rowIndex;

  const DanmakuCommentWidget({
    super.key,
    required this.height,
    required this.rowIndex,
  });

  @override
  State<DanmakuCommentWidget> createState() => _DanmakuCommentWidgetState();
}

class _DanmakuCommentWidgetState extends State<DanmakuCommentWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _slideAnimation;
  List<LeaderboardCommentEntity> _comments = [];
  int _currentCommentIndex = 0;

  @override
  void initState() {
    super.initState();
    _initializeComments();
    _setupAnimation();
    _startAnimation();
  }

  void _initializeComments() {
    // 获取排行榜评论数据
    final allComments = leaderboardManager.getCommentsSortedByTime();
    if (allComments.isEmpty) {
      _comments = [
        LeaderboardCommentEntity(
          commentId: 'default_${widget.rowIndex}',
          authorId: 'user_001',
          content: 'Welcome to Vamos community!',
          commentTime: DateTime.now(),
        ),
      ];
    } else {
      // 为每一排分配不同的评论
      _comments = [];
      for (int i = widget.rowIndex; i < allComments.length; i += 3) {
        _comments.add(allComments[i]);
      }

      // 如果该排没有评论，添加默认评论
      if (_comments.isEmpty) {
        _comments = [
          LeaderboardCommentEntity(
            commentId: 'default_${widget.rowIndex}',
            authorId: 'user_00${(widget.rowIndex % 8) + 1}',
            content: 'Great community discussion here!',
            commentTime: DateTime.now(),
          ),
        ];
      }
    }
  }

  void _setupAnimation() {
    int duration;
    switch (widget.rowIndex) {
      case 0:
        duration = 8;
        break;
      case 1:
        duration = 12;
        break;
      case 2:
        duration = 10;
        break;
      default:
        duration = 10;
    }

    _animationController = AnimationController(
      duration: Duration(seconds: duration),
      vsync: this,
    );

    _slideAnimation = Tween<double>(begin: 1.0, end: -1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.linear),
    );
  }

  void _startAnimation() {
    _animationController.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        // 动画完成后切换到下一条评论
        setState(() {
          _currentCommentIndex = (_currentCommentIndex + 1) % _comments.length;
        });
        _animationController.reset();
        _animationController.forward();
      }
    });

    int delayMs;
    switch (widget.rowIndex) {
      case 0:
        delayMs = 0;
        break;
      case 1:
        delayMs = 0;
        break;
      case 2:
        delayMs = 0;
        break;
      default:
        delayMs = widget.rowIndex * 1000;
    }

    Future.delayed(Duration(milliseconds: delayMs), () {
      if (mounted) {
        _animationController.forward();
      }
    });
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_comments.isEmpty) {
      return SizedBox(height: widget.height);
    }

    return SizedBox(
      height: widget.height,
      child: AnimatedBuilder(
        animation: _slideAnimation,
        builder: (context, child) {
          return Transform.translate(
            offset: Offset(
              _slideAnimation.value * (MediaQuery.of(context).size.width + 200),
              0,
            ),
            child: Container(
              alignment: Alignment.centerLeft,
              child: _buildCommentBubble(),
            ),
          );
        },
      ),
    );
  }

  Widget _buildCommentBubble() {
    final comment = _comments[_currentCommentIndex];

    // 获取用户信息
    final user = userManager.getUserById(comment.authorId);
    final avatarUrl = user?.profileImage ?? 'assets/images/avatar1.png';

    return Container(
      height: widget.height,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment(0.00, 0.50),
          end: Alignment(1.00, 0.50),
          colors: [
            const Color(0xFFCEF672),
            Colors.white.withValues(alpha: 0.2),
          ],
        ),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(100.r),
          bottomLeft: Radius.circular(100.r),
        ),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 用户头像
          ClipOval(
            child: Image.asset(
              avatarUrl,
              width: 30.w,
              height: 30.w,
              fit: BoxFit.cover,
              errorBuilder: (context, error, stackTrace) {
                return Container(
                  width: 20.w,
                  height: 20.w,
                  decoration: BoxDecoration(
                    color: Colors.grey[400],
                    shape: BoxShape.circle,
                  ),
                  child: Icon(Icons.person, size: 12.sp, color: Colors.white),
                );
              },
            ),
          ).paddingRight(8),

          // 评论文字（限制为单行）
          Flexible(
            child: Text(
              comment.content,
              style: TextStyle(
                color: Colors.black,
                fontSize: 12.sp,
                fontFamily: GoogleFonts.roboto().fontFamily,
                fontWeight: FontWeight.w500,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ).paddingRight(12.w),
    );
  }
}
